package org.cqut.system.resource.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.cqut.system.resource.domain.Resource;
import org.cqut.system.resource.service.ResourceService;
import org.cqut.system.resource.mapper.ResourceMapper;
import org.cqut.system.resource_course.domain.ResourceCourse;
import org.cqut.system.resource_course.mapper.ResourceCourseMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author XiAoXu
 */
@Service
public class ResourceServiceImpl extends ServiceImpl<ResourceMapper, Resource>
        implements ResourceService {
    @Autowired
    private ResourceMapper resourceMapper;

    @Autowired
    private ResourceCourseMapper resourceCourseMapper;

    @Override
    public IPage<Resource> getResourceList(int page, int limit, String condition) {
        return resourceMapper.selectResourceList(new Page<>(page, limit), condition);
    }

    @Override
    public boolean rename(Resource resource) {
        UpdateWrapper<Resource> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("resource_id", resource.getResourceId());
        updateWrapper.set("resource_name", resource.getResourceName());
        return update(updateWrapper);
    }

    @Override
    public boolean removeResourceById(String resourceId) {
        //1.检查是否有课程引用了资源
        QueryWrapper<ResourceCourse> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("resource_id", resourceId);
        List<ResourceCourse> resourceCourses = resourceCourseMapper.selectList(queryWrapper);
        //2.不存在则删除
        if (resourceCourses.isEmpty()) {
            return removeById(resourceId);
        } else {
            return false;
        }
    }
}




